package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 5);
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //2.生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //封装发送的消息
        ProducerRecord<String, String> record = new ProducerRecord<String, String>("itheima-topic", "key-1","hello kafka ");

        //3.发送消息
        /*
            1. 发送消息的两种方式：
                a. 同步发送: producer.send(record);
                b. 异步发送: producer.send(record, new Callback(){});
            2. 区别
                a. 同步是传一个消息参数
                b. 异步是传两个消息参数，第二个参数给回调接口对象
                c. 异步比同步效率高: 同步：1321132770  异步：511747823
         */
        //同步发

//        RecordMetadata recordMetadata = producer.send(record).get();
//        System.out.println(recordMetadata.offset());   //

        //异步消息发送
        long start = System.nanoTime();
        for (int i = 1; i <= 100; i++) {
            producer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if (e != null) {
                        System.out.println("记录异常信息到日志表中");
                    }
                    System.out.println(recordMetadata.offset());   //2
                }
            });
        }
        long end = System.nanoTime();
        System.out.println(end - start);


        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }

}